package rpc.netty.client;

import com.alibaba.fastjson2.JSON;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import rpc.common.MyMessageProtocol;
import rpc.common.MyInvocation;

import java.nio.charset.StandardCharsets;

/**
 * 自定义客户端处理器
 */
public class MyClientHandler extends SimpleChannelInboundHandler<MyMessageProtocol> {
    private MyInvocation myInvocation;
    private String result;

    /**
     * 通道激活
     */
    @Override
    public void channelActive(ChannelHandlerContext ctx) {
        String interfaceName = myInvocation.getInterfaceName();
        String methodName = myInvocation.getMethodName();
        String parameterTypes = JSON.toJSONString(myInvocation.getParameterTypes());
        String parameters = JSON.toJSONString(myInvocation.getParameters());
        String content = interfaceName + "#" + methodName + "#" + parameterTypes + "#" + parameters;

        MyMessageProtocol myMessageProtocol = new MyMessageProtocol();
        byte[] contentByte = content.getBytes(StandardCharsets.UTF_8);
        myMessageProtocol.setLength(contentByte.length);
        myMessageProtocol.setContent(contentByte);

        //写入返回内容
        ctx.write(myMessageProtocol);
        //刷新
        ctx.flush();
    }

    /**
     * 通道读取
     */
    @Override
    protected void channelRead0(ChannelHandlerContext channelHandlerContext, MyMessageProtocol myMessageProtocol) {
        System.out.println("channelRead0方法执行");
        String content = new String(myMessageProtocol.getContent(), StandardCharsets.UTF_8);
        System.out.println("接收消息：" + content);
        String[] contents = content.split("#");
        result = contents[4];
    }

    /**
     * 通道读取完成
     */
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) {
        ctx.close();
    }

    public void setMyInvocation(MyInvocation myInvocation) {
        this.myInvocation = myInvocation;
    }

    public String getResult() {
        return result;
    }
}
